<?php


namespace app\middleware;


use app\common\tool\HttpCode;
use app\common\tool\JwtAuth;
use app\common\exception\JwtException;
use think\Exception;

class Auth
{
    public function handle($request, \Closure $next)
    {
        $jwtAuth = new JwtAuth(
            config('secure.jwt_alg'),
            config('secure.verify_salt')
        );

        $headerName = config('secure.token_name');

        $jwt = $request->header($headerName, '');

        if (!$jwt) {
            throw new JwtException(['msg' => '未登录', 'code' => HttpCode::CLIENT_ERROR]);
        }

        try {
            $jwtAuth->verify($jwt);
        }catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            throw new JwtException(['msg' => '签名不正确', 'code' => HttpCode::CLIENT_ERROR]);
        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用            throw new JwtException(['msg' => '签名不正确', 'code' => HttpCode::JWT_ERROR]);
            throw new JwtException(['msg' => '签名未到生效时间', 'code' => HttpCode::CLIENT_ERROR]);
        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
            throw new JwtException(['msg' => '签名已过期', 'code' => HttpCode::CLIENT_ERROR]);
        }catch(Exception $e) {  //其他错误
            throw new JwtException(['msg' => $e->getMessage(), 'code' => HttpCode::CLIENT_ERROR]);
        }

        return $next($request);
    }
}